import { ref, onMounted } from 'vue'
import type { Ref } from 'vue'
import { getOrgList } from '/@/api/organization'
import { useMessage } from '/@/hooks/web/useMessage'

const { createMessage } = useMessage();

function treeFormatTransform(s) {
  if (!s) return [];
  let t = []
  if (s.length) {
    t = s.map(e => ({
      title: e.orgName,
      label: e.orgName,
      value: e.id,
      orgId: e.id,
      children: e.children ? [...treeFormatTransform(e.children)] : undefined
    }))
  }
  return t;
}

export default function UseOrganizations(loading: Ref) {
  let organizations = ref([]);
  const getOrganizations = async () => {
    loading.value = true;
    let { data: ret, code, msg } = await getOrgList({ orgName: '' });
    loading.value = false;
    if (code === 200) {
      organizations.value = treeFormatTransform(ret);
      // console.log('organizations.value', organizations.value);
    } else {
      createMessage({
        message: msg,
        type: 'error'
      });
    }
  }
  onMounted(getOrganizations);
  return {
    organizations,
    getOrganizations
  }
}